/**
 * Created by H2 on 2016/1/15.
 *
 * 一切从现在开始还来得及
 */

$(function(){

    /* URL */
    var comboDetailURL = "/api/client/comb/getCombDetail";                   //组合总数据接口
    var comboDetailPiePicURL = "/api/client/comb/getcombItem";               //饼状图接口
    var comboDetailFeaturePicURL = "/api/client/comb/getComboFeature";       //组合特性接口
    var comboDetailEvaluateURL = "/api/client/combComment/commentlist";      //评论接口
    var comboDetailEvaluateTotalURL = "/api/client/combComment/comentcount"; //评论总数接口
    var comboDetailSendEvaluateURL = "/api/client/combComment/sendcomment";  //评论发送接口
    var comboDetailFlowPicURL = "/api/client/comb/getCombFlow";              //流动堆积图接口

    /* Map */
    var comboDetailMap = {
        "#comboDetail-info-temp" : "#comboDetail-info",
        "#comboDetail-property-temp" : "#comboDetail-property",
        "#comboDetail-exhibition-temp" : "#comboDetail-exhibition",
        "#comboDetail-infoDesc-temp" : "#comboDetail-infoDesc"
    };

    var comboDetailPiePicMap = {
        "#comboDetail-pieChartTable-temp" : "#comboDetail-pieChartTable"
    };

    var comboDetailEvaluateMap = {
        "#detail-evaluate-content-temp" : "#comboDetail-evaluate-content"
    };

    /*定义临时变量*/
    var jsonData = '';
    var totalData = '';
    var pieChartdata = [];
    var trustsFeaturedata = [];
    var foundFeaturedata = [];
    var comboFeaturedata = [];

    var mainLine = [];
    var line70 = [];
    var line90 = [];
    var ca = {};
    var fd = {};
    var hb = {};
    var tr = {};

    //定义分页变量
    var count = 3;
    var nowPage = 1;

    /* 获取页面Id值 */
    $.ajax({
        type: "GET",
        async: false,
        url: comboDetailURL,
        data: {
            "combId": $('.comboDetail').data("comboid"),
            "t": now()
        },
        dataType: "json",
        success: function (data) {
            jsonData = data;
        }
    });

    /* 调用函数 */
    doRender(
        comboDetailURL,
        {
            "combId" : jsonData.data.comboComboValuesAssetPackInstance.comboId,   /* a:b   a为？号后边查询项，跟后台命名保持一致，*/
                                                                                  /*b为渲染的具体数据，其格式要与后台数据接口一致。*/
            "t" : now()
        },
        comboDetailMap
    );

    /* 获取pieTable数据 */
    doRender(
        comboDetailPiePicURL,
        {
            "combId" : jsonData.data.comboComboValuesAssetPackInstance.comboId,
            "t" : now()
        },
        comboDetailPiePicMap,
        onloadClick
    )

    /* JsRender 自定义标签 */
    $.views.tags({
        showStars: function(arNumber){
            var res = "";
            if(arNumber){
                for(var i=0; i<arNumber; i++){
                    res += '<span class="pList-detail-collect icon-collect-pitchon pull-center" style="line-height: 45px;"></span>';
                }

                for(var j=0; j<5-arNumber; j++){
                    res += '<span class="pList-detail-collect pull-center icon-collect-1" style="line-height: 45px;"></span>';
                }
                return res;
            }else{
                for(var i=0; i<5; i++){
                    res += '<span class="pList-detail-collect pull-center icon-collect-1" style="line-height: 45px;"></span>';
                }
                return res;
            }
        }
    });

    /* 获取饼状图的数据 */
    $.ajax({
        type: "GET",
        async: false,
        url: comboDetailPiePicURL,
        data: {
            "combId": $('.comboDetail').data("comboid"),
            "t": now()
        },
        dataType: "json",
        success: function (data) {
            if(data.money.itemPercent!=null){
                pieChartdata.push({
                    name: '现金 '+ (data.money.itemPercent).toFixed(2) +'%',
                    y: data.money.itemPercent,
                    color:'#1885c6'
                })
            }
            if(data.h_found.percent!=null){
                pieChartdata.push({
                    name: '货币 '+ (data.h_found.percent).toFixed(2) +'%',
                    y: data.h_found.percent,
                    color:'#ee7a39'
                })
            }
            if(data.z_found.percent!=null){
                pieChartdata.push({
                    name: '债券 '+ (data.z_found.percent).toFixed(2) +'%',
                    y:data.z_found.percent,
                    color:'#f2594b'
                })
            }
            if(data.trusts.percent!=null){
                pieChartdata.push({
                    name: '信托 '+ (data.trusts.percent).toFixed(2) +'%',
                    y: data.trusts.percent,
                    color:'#4ebde3'
                })
            };
        }
    });


    /* 获取时间函数 */
    function addYears(date,y) {
        date.setFullYear(date.getFullYear() + y);
        return date;
    };
    function addDays(date,d) {
        date.setDate(date.getDate() + d);
        return date;
    };
    function lengthDate(startDate,endDate){
        var second=endDate.getTime()-startDate.getTime();
        return second/(24*60*60*1000);
    }
    function getDayMix(startdate,enddate){
        var start=new Date(startdate.replace(/-/g, "/"));
        var end=new Date(enddate.replace(/-/g, "/"));
        return (end-start)/(24*60*60*1000);
    }
    function getDate(date){
        return new Date(date.replace(/-/g, "/"));
    }
    function addOneDay(date,n){
        now=getDate(date.replace(/-/g, "/"));
        return (new Date((now/1000+n*86400)*1000));
    }


    // 组合特性图 和 组合净值图
    $.ajax({
        type: "GET",
        async: false,
        url: comboDetailFeaturePicURL,
        data: {
            "comboId": $('.comboDetail').data("comboid"),
            "t": now()
        },
        dataType: "json",
        success: function (data) {
             comboFeaturedata = [
              [data.combos.pExpectedRisk * 100, data.combos.pExpectedBenefitRate * 100]
            ];
            for(var i in data.items){
                if(data.items[i].pType == 11){
                    foundFeaturedata.push([data.items[i].pExpectedRisk*100, data.items[i].pExpectedBenefitRate*100]);
                }else if(data.items[i].pType == 1){
                    trustsFeaturedata.push([data.items[i].pExpectedRisk*100, data.items[i].pExpectedBenefitRate*100]);
                }
            }

            //组合净值图
            var k = Math.log(data.valueLine.p2y)/data.valueLine.p2x;
            var kUp70 = Math.log(data.valueUp70Line.p2y)/data.valueUp70Line.p2x;
            var kUp90 = Math.log(data.valueUp90Line.p2y)/data.valueUp90Line.p2x;
            var kDown70 = Math.log(2-data.valueDown70Line.p2y)/data.valueDown70Line.p2x;
            var kDown90 = Math.log(2-data.valueDown90Line.p2y)/data.valueDown90Line.p2x;

            var lastData = addYears(new Date(),Math.ceil(data.valueLine.p2x));
            var tempData = new Date();
            var length = lengthDate(new Date(), lastData);

            for(var i=0; tempData.getTime() <= lastData.getTime(); i++){
               var x = (data.valueLine.p2x/length)*i;  //划分x轴
               //console.log(x);
               var y = Math.exp(k*x);

               var y1=Math.exp(kUp70*x);
               var y2=-Math.exp(kDown70*x)+2;

               var y3=Math.exp(kUp90*x);
               var y4=-Math.exp(kDown90*x)+2;
               mainLine.push([x,y]);
               line70.push([x,y1,y2]);
               line90.push([x,y3,y4]);
               tempData = addDays(tempData,1);
            }
        }
    });


    /*流动堆积图*/
    $.ajax({
        type: "GET",
        async: false,
        url: comboDetailFlowPicURL,
        data: {
            "comboId": $('.comboDetail').data("comboid"),
            "t": now()
        },
        dataType: "json",
        success: function (d) {
            var dispatch= d.dispatch_time;
            ca={name: "现金",data:[], marker: {enabled: false},color:'#1885c6',
                fillColor: {
                    linearGradient: {
                        y1: 0,
                        y2: 1
                    },
                    stops: [
                        [0, '#1885c6'],
                        [1, '#ffffff']
                    ]
                }
            };
            fd={name:"股票基金",data:[], marker: {enabled: false},color:'#f2594b',
                fillColor: {
                    linearGradient: {
                        y1: 0,
                        y2: 1
                    },
                    stops: [
                        [0, '#f2594b'],
                        [1, '#ffffff']
                    ]
                }
            };
            hb={name:"货币基金",data:[], marker: {enabled: false},color:'#ee7a39',
                fillColor: {
                    linearGradient: {
                        y1: 0,
                        y2: 1
                    },
                    stops: [
                        [0, '#ee7a39'],
                        [1, '#ffffff']
                    ]
                }
            };
            tr={name:"信托",data:[], marker: {enabled: false},color:'#4ebde3',
                fillColor: {
                    linearGradient: {
                        y1: 0,
                        y2: 1
                    },
                    stops: [
                        [0, '#4ebde3'],
                        [1, '#ffffff']
                    ]
                }
            };
            var caHigh=0,fdHigh=0,hbHigh=0,trHigh=0;

            if(d.data.trust!=null){
                for(one in d.data.trust){
                    var n=parseInt(one,10)+1
                    if(d.data.trust[n]!='undefined'&& d.data.trust[n]!=null){
                        var nowAmount=d.data.trust[one].amount;
                        var firstDate=getDate(d.data.trust[one].td);
                        var mixDay=getDayMix(d.data.trust[one].td,d.data.trust[n].td)
                        for(var i=0;i<mixDay;i++){
                            var nextDay=addOneDay(d.data.trust[one].td,i);
                            var afterDay=addOneDay(d.data.trust[one].td,i+1);
                            tr.data.push(nowAmount);
                            for(two in dispatch){
                                t=getDate(dispatch[two].dispatch_time);
                                if((t.getTime()>=nextDay.getTime())&&(t.getTime()<afterDay.getTime())){
                                    nowAmount=nowAmount-dispatch[two].amount;
                                    tr.data.push(nowAmount);
                                }
                            }

                        }
                        if(nowAmount>trHigh){
                            trHigh=nowAmount;
                        }
                    }
                }
            }
            if(d.data.cash!=null){
                for(one in d.data.cash){
                    var n=parseInt(one,10)+1;
                    if(d.data.cash[n]!='undefined'&& d.data.cash[n]!=null){
                        var nowAmount=0+d.data.cash[one].amount;
                        var firstDate=getDate(d.data.cash[one].td);
                        var mixDay=getDayMix(d.data.cash[one].td,d.data.cash[n].td);
                        for(var i=0;i<mixDay;i++){
                            var nextDay=addOneDay(d.data.cash[one].td,i);
                            var afterDay=addOneDay(d.data.cash[one].td,i+1);
                            ca.data.push(nowAmount);
                            for(two in dispatch){
                                t=getDate(dispatch[two].dispatch_time);
                                if((t.getTime()>=nextDay.getTime())&&(t.getTime()<afterDay.getTime())){
                                    nowAmount=nowAmount+dispatch[two].amount;
                                    ca.data.push(nowAmount);
                                }
                            }
                        }
                        if(nowAmount>caHigh){
                            caHigh=nowAmount;
                        }
                    }
                }
            }

            if(d.data.fund!=null){
                for(one in d.data.fund){
                    n=parseInt(one,10)+1
                    if(d.data.fund[n]!='undefined'&& d.data.fund[n]!=null){
                        nowAmount=0+d.data.fund[one].amount;
                        firstDate=getDate(d.data.fund[one].td);
                        mixDay=getDayMix(d.data.fund[one].td,d.data.fund[n].td)
                        for(i=0;i<mixDay;i++){
                            var nextDay=addOneDay(d.data.fund[one].td,i);
                            var afterDay=addOneDay(d.data.fund[one].td,i+1);
                            fd.data.push(nowAmount);
                            for(two in dispatch){
                                t=getDate(dispatch[two].dispatch_time);
                                if((t.getTime()>=nextDay.getTime())&&(t.getTime()<afterDay.getTime())){
                                    fd.data.push(nowAmount);
                                }
                            }
                        }
                        if(nowAmount>fdHigh){
                            fdHigh=nowAmount;
                        }
                    }
                }
            }
            if(d.data.HBfund!=null){
                for(one in d.data.HBfund){
                    n=parseInt(one,10)+1;
                    if(d.data.HBfund[n]!='undefined'&& d.data.HBfund[n]!=null){
                        nowAmount=0+d.data.HBfund[one].amount;
                        firstDate=getDate(d.data.HBfund[one].td);
                        mixDay=getDayMix(d.data.HBfund[one].td,d.data.HBfund[n].td)
                        for(i=0;i<mixDay;i++){
                            var nextDay=addOneDay(d.data.HBfund[one].td,i);
                            var afterDay=addOneDay(d.data.HBfund[one].td,i+1);
                            hb.data.push(nowAmount);
                            for(two in dispatch){
                                t=getDate(dispatch[two].dispatch_time);
                                if((t.getTime()>=nextDay.getTime())&&(t.getTime()<afterDay.getTime())){
                                    hb.data.push(nowAmount);
                                }
                            }
                        }
                        if(nowAmount>hbHigh){
                            hbHigh=nowAmount;
                        }
                    }
                }
            }
        }
    });



    /* 表格点击事件 */
    function onloadClick() {
        $(".pieChartSlideContent").click(function () {
            $(this).nextAll("div.indicate").slideToggle();
            $(this).find("i").toggleClass("iconIndicateDown");
        });
    }

    /* 饼状图 */
   $("#comboDetail-pieChart-content").highcharts({
       chart: {
           type: 'pie',
           marginTop:50,
           marginLeft:-50,
           marginBottom:50
       },
       title:{
           text:'资产总规模（万元)',
           verticalAlign: 'bottom',
           style: {
               color: '#949494',
               fontWeight: 'bold'
           },
           x:-25,
           y:-10
       },
       plotOptions:{
           pie: {
               cursor: 'pointer',
               showInLegend: true,
               allowPointSelect: false,
               dataLabels:{
                   enabled: false
               }
           }
       },
       tooltip:{
           enabled: true
       },
       legend:{
           align:'right',
           layout :'vertical',
           floating :true,
           verticalAlign : 'top',
           y: 100,
           x:-150,
           itemMarginBottom:4
       },
       credits:{
                enabled: false
       },
       series: [{
           data:pieChartdata
       }]
   });


   /* 区域图 */
   $("#flowAccumulateDiag").highcharts({
       chart:{
           type:'area',
           marginTop:50
       },
       title:null,
       xAxis:{
           type: 'category',
           labels: {
               formatter: function() {
                   if(this.value==0){
                       return "今天";
                   }else{
                       return parseInt(this.value/30)+"月";
                   }
               },
               enabled: true
           },
           tickInterval:30
       },
       yAxis:{
           title:{
             text:'资产(万元)',
             rotation:0,
             offset:0,
             align:'high',
             style:{
                 fontWeight:600
             },
             floating: true,
             y:-20
           },
           labels: {
               formatter: function () {
                   return this.value / 10000;
               }
           }
       },
       credits:{
           enabled: false
       },
       tooltip:{
           shared: true,
           headerFormat:'',
           valueSuffix: ' 元'
       },
       legend:{
           floating:true,
           align:'right',
           verticalAlign:'top'
       },
       plotOptions: {
           area: {
               stacking: 'normal'
           }
       },
       series:[tr,ca,hb,fd]
   });


    /* 组合特性图 (点状图)*/
    $("#comboPropertyDiag").highcharts({
        chart:{
            marginTop:50,
            marginLeft:80,
            marginBottom:70,
            zoomType:"xy"
        },
        title:null,
        xAxis:{
            title:{
                text:'风险(%)',
                offset:0,
                align:'high',
                style:{
                    fontWeight:600
                },
                y:30
            },
            tickWidth:1,
            tickLength:2,
            tickPosition:'inside'

        },
        yAxis:{
            title:{
                text:'收益(%)',
                rotation:0,
                offset:0,
                align:'high',
                style:{
                    fontWeight:600
                },
                floating: true,
                y:-20
            },
            gridLineWidth:1,
            gridLineDashStyle:'Dash'
        },
        credits:{
            enabled:false
        },
        tooltip:{
            enabled:true,
            borderColor:'#274B61',
            crosshairs: true,
            formatter: function () {
                var s = '<p style="color:'+this.color+';">' + this.series.name + '</p>' + '<br/>' + '分险: '+this.x.toFixed(2) +'<br/>'+ '收益: ' +
                    this.y.toFixed(2) + '%';
                return s;
            }
        },
        legend:{
            floating:true,
            align:'right',
            verticalAlign:'top',
            symbolPadding:10
        },
        series:[{
            type:'scatter',
            name:'组合',
            data: comboFeaturedata,
            color:'#274b61',
            marker:{
                radius:13
            }
        },{
            type:'scatter',
            name:'基金',
            color:'#d02919',
            data: foundFeaturedata,
            marker:{                         //图例大小及形状
                radius:8,
                symbol: 'triangle'
            }
          },{
            type:'scatter',
            name:'信托',
            color:'#4ebde3',
            data: trustsFeaturedata,
            marker:{
                radius:8
            }
        }]
    });


    /* 组合净值图 (区域图) */
    $("#comboNetWorthDiag").highcharts({
        chart:{
            marginTop:50,
            marginLeft:80,
            marginBottom:70
        },
        xAxis:{
            tickWidth:0,
            labels: {
                formatter: function() {
                    if(this.value==0){
                        return '今天';
                    }else{
                        return this.value;
                    }
                },
                enabled: true
            }
        },
        yAxis:{
            title:{
                text:'净值',
                rotation:0,
                offset:0,
                align:'high',
                style:{
                    fontWeight:600
                },
                floating: true,
                y:-25,
                x:-10
            }
        },
        title:null,
        credits:{
            enabled:false
        },
        tooltip:{
            shared:true,
            crosshairs: true,
            formatter : function(){
                var s = '';
                $.each(this.points, function () {
                   s += this.series.name +'  ' + this.x.toFixed(2) +'-'+ this.y.toFixed(2)+'%'+ '<br>';
                });
                return s;
            }
        },
        legend:{
            floating:true,
            align:'right',
            verticalAlign:'top'
        },
        series:[{
            name: '净值期望值',
            data: mainLine,
            zIndex: 1,
            color:'#b0becb',
            marker: {
                fillColor: '#b0becb',
                lineWidth: 1
            }
        },{
            name: '70%置信度',
            type: 'arearange',
            data: line70,
            color:'#f2f3f6',
            zIndex: 0
        },{
            name: '90%置信度',
            type: 'arearange',
            data: line90,
            color:'#e0e7ee',
            zIndex: 0
        }]
    });

    //获取total总数
    $.ajax({
        type: "get",
        async: false,
        url: comboDetailEvaluateTotalURL,
        data: {
            "combId": $('.comboDetail').data("comboid")
        },
        dataType:"json",
        success: function(data){
            totalData = data.data;     //totalData 为评论的总条数
        }
    });

    //评论分页实现
    function commentRender($obj, url, comboid, nowPage, count, map, callback) {
        doRender(
            url,
            {
                "combId": comboid,
                "start": (nowPage - 1) * count,
                "length": count
                //"t": now()
            },
            map,
            function () {
                if (totalData >= 0) {
                    //在目标节点后append分页组件
                    $obj.append(genPagination(totalData, count, nowPage));
                    initPagination($obj, url, comboid, nowPage, count, map, callback);
                }
            }
        )
    }

    //分页实现
    function initPagination($obj, url, comboid, nowPage, count, map, callback) {

        $('.jcb-page-first').click(function () {
            if (nowPage == 1) return;
            nowPage = 1;
            callback($obj, url, comboid, nowPage, count, map, callback);
        });

        $('.jcb-page-last').click(function () {
            if (nowPage == $(this).data('page')) return;
            nowPage = $(this).data('page');
            callback($obj, url, comboid, nowPage, count, map, callback);
        });

        $('.jcb-page-next').click(function () {
            if (nowPage >= $(this).data('page')) return;
            nowPage++;
            callback($obj, url, comboid, nowPage, count, map, callback);
        });

        $('.jcb-page-pre').click(function () {
            if (nowPage <= $(this).data('page')) return;
            nowPage--;
            callback($obj, url, comboid, nowPage, count, map, callback);
        });

        $('.jcb-page-this').click(function () {
            if (nowPage == $(this).data('page')) return;
            nowPage = $(this).data('page');
            callback($obj, url, comboid, nowPage, count, map, callback);
        });
    }

    commentRender($('#comboDetail-evaluate-content'), comboDetailEvaluateURL, jsonData.data.comboComboValuesAssetPackInstance.comboId, nowPage, count, comboDetailEvaluateMap, commentRender);

    //提交评论
    $('#send-evaluate').click(function () {
        var commentContent = $('#my-comment').val();
        if (commentContent == '') {
            $(this).prev().html('亲，请您填写评论后再提交哦！'). fadeIn();
            return;
        }
        //alert(commentContent);
        doPost(
            comboDetailSendEvaluateURL,
            {
                "comment": commentContent,
                "combId" : jsonData.data.comboComboValuesAssetPackInstance.comboId
            },
            function () {
                $('#myEvaluate').modal('hide').find('#error-msg').fadeOut();
                commentRender($('#comboDetail-evaluate-content'), comboDetailEvaluateURL, jsonData.data.comboComboValuesAssetPackInstance.comboId, nowPage, count, comboDetailEvaluateMap, commentRender);
            }
        );
    });

});
